package leetcode.code0114;

import leetcode.helper.HelpDebug;
import leetcode.helper.tree.TreeArray;
import leetcode.helper.tree.TreeNode;

public class Solution {
	public void flatten(TreeNode root) {
		if (root == null)
			return;
		root = this.f(root);
	}

	public TreeNode f(TreeNode root) {
		if (root.left == null && root.right == null) {
			return root;
		}
		TreeNode right = null;
		if (root.right != null) {
			right = this.f(root.right);
		}
		if (root.left != null) {
			TreeNode left = this.f(root.left);
			root.right = left;
			root.left = null;
			this.rightest(left).right = right;
		}
		return root;
	}

	private TreeNode rightest(TreeNode root) {
		if (root.right == null)
			return root;
		return this.rightest(root.right);
	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.flatten(TreeArray.array2tree(HelpDebug.str2array4("[1,null,2,3]")));
	}
}
